<?php
/**
 *  公共服务
*/

namespace app\api\service;

use app\api\model\Customer;
use app\common\ApiClient;
use app\common\RedisClient;
use app\facade\Basic;
use think\facade\Cache;
use think\facade\Config;

class Common
{
    #系统语言和三方语言 关系映射
    const LANGUAGE_CODE = [
        'en' => 'English',
        'es' => 'Spanish',
        'fr' => 'French',
        'it' => 'Italian',
        'de' => 'German',
        'ru' => 'Russian',
        'pt' => 'Portuguese',
        'ar' => 'Arabic',
        'ja' => 'Japanese',
        'ko' => 'Korean',
        'vn' => 'Vietnamese',
        'zh' => 'Chinese'
    ];
    /**
     *  用户登录
    */

    public function getEmailCode($param)
    {

        $result = Customer::where('email',$param['email'])
            ->where('is_del','=','0')
            ->find();

        if ( $param['scene'] == 1 && $result ) {
            return Basic::data(1,'getEmailCode.emailAlreadyExists');
        } else if ( $param['scene'] == 2 && !$result ) {
            return Basic::data(1,'getEmailCode.emailNotExist');
        }

        $data['code'] = getVerifyCode(6);
        $data['to'] = $param['email'];
        $data['subject'] = 'get Register Email Code';
        $content = <<<HTML
     code: {$data['code']}
HTML;
        $data['content'] = $content;
        return MailCheck::create($data);
    }
    /**
     * 批量翻译
     */
    public function translate($param){
        $content = $param['content'] ?? '';
        $target = $param['target_language'] ?? '';
        $target = self::LANGUAGE_CODE[$target] ?? '';
        $isTranslate = true;
        if(!$isTranslate){
            return Basic::data( 0, 'common.success',json_decode($content,true));
        }
        if(!$content || !$target){
            return Basic::data( 100002, 'common.parameterError');
        }

        $redis = new RedisClient();

        #从redis取数据，不存在放入待翻译池
        $content = json_decode($content,true);
        foreach ($content as $k=>$value){
            if(empty($k) || empty($value)){
                continue;
            }
            $ks[] = $k;
            $keys[] = $this->getRedisKey($target,$k);
        }
        $return = $redisContent = $redis->hMGet('translate',$keys);
        $ret = [];
        foreach ($return as $key=>$v){
            if($v){
                $ret[$ks[$key]]= $v;
            }else{
                $ret[$ks[$key]] = $content[$ks[$key]];
            }
        }
        return Basic::data(0,'common.success',$ret);
    }

    /**
     * 脚本翻译
     */
    public function translateForScript($param){
        $content = $param['content'] ?? '';
        $target = $param['target_language'] ?? '';
        $target = self::LANGUAGE_CODE[$target] ?? '';
        $isTranslate = true;
        if(!$isTranslate){
            return Basic::data( 0, 'common.success',json_decode($content,true));
        }
        if(!$content || !$target){
            return Basic::data( 100002, 'common.parameterError');
        }
        $toTranslate = [];
        $toTranslateKey = [];
        $redis = new RedisClient();
        $return = [];
        $tanslateReturn = '';
        #从redis取数据，不存在放入待翻译池
        $content = json_decode($content,true);
        foreach ($content as $k=>$value){
            if(empty($k) || empty($value)){
                continue;
            }
            # 将原始值存入redis
            $original_key = $this->getRedisKey('original',$k);
            $original_data = $redis->hGet('translate',$original_key);
            if(!$original_data){
                $redis->hSet('translate',$original_key,$value);
            }

            $key = $this->getRedisKey($target,$k);
            $redisContent = $redis->hGet('translate',$key);
            if(!$redisContent){
                $toTranslate[] = $value;
                $toTranslateKey[] = $k;
                continue;
            }
            $return[$k] = $redisContent;
        }
        #查询第三方 将结果存redis
        if(!empty($toTranslate)){
            #请求第三方接口拿翻译数据
            $tanslateReturn = $this->getTranslateData($toTranslate,$target);
            #处理返回数据并存redis
            if($tanslateReturn){
                foreach ($tanslateReturn as $key => $item){
                    #将翻译数据 与提交数据匹配
                    $returnKey = $toTranslateKey[$key]??'';
                    $key =  $this->getRedisKey($target,$returnKey);
                    if($returnKey){
                        if($item['status']  == 'success'){
                            $redis->hSet('translate',$key,$item['data']);
                        }else{
                            #因为脚本只有一条数据  可以直接返回
                            return Basic::data( 100002, 'common.error');
                        }
                        $return[$returnKey] = $item;
                    }
                }
            }
        }
        return Basic::data( 0, 'common.success',$return);
    }
     public function singleTranslate($value,$lang)
     {
         $tran = md5($value);
         $translate = [
             'content' => json_encode([$tran => $value]),
             'target_language' => $lang,
         ];
         $tran_return = $this->translate($translate);
         return $value = $tran_return['data'][$tran] ?? $value;
     }

    /**
     * @author xuzhong
     * @param $toTranslate
     * @param $target
     * @return array
     * 调三方接口拿翻译数据 优先取缓存
     */
    public function getTranslateData($toTranslate,$target){
        $data = [];
        foreach ($toTranslate as $v ){
            $key = $this->getRedisKey($target,md5($v));
            $vData = Cache::get($key);
            if(empty($vData)){
                $param = [
                    'text' =>$v,
                    'target_language' =>$target
                ];

                $domain = Config::get('domain')['prod']['erpapi'];
                $apiClient = new ApiClient($domain);
                $return = $apiClient->post('/api/support/translate', ['body' =>json_encode($param)]);
                if(!isset($return['status']) || $return['status'] != 'success'|| !isset($return['text'])){
                    $data[] =[
                        'status' => $return['status']?? 'fail',
                        'data' => $v
                    ];
                    continue;
                }
                Cache::set($key,$return['text']);
                $vData = $return['text'];
            }
            $data[] =[
                'status' => 'success',
                'data' => $vData
             ];
        }

        return $data;
    }
    private function getRedisKey($target,$md5){
        $str = 'tanslate:%s:%s';
        return sprintf($str,$target,$md5);
    }
}
